package ynu.edu.user.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import ynu.edu.common.exception.BusinessException;
import ynu.edu.common.result.ResultCode;
import ynu.edu.user.util.JwtUtil;

/**
 * JWT拦截器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtInterceptor implements HandlerInterceptor {

    private final JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        
        // 如果是OPTIONS请求，直接放行
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }
        
        // 检查是否需要验证token的路径
        String uri = request.getRequestURI();
        if (isExcludedUri(uri)) {
            return true;
        }
        
        // 验证token
        if (!StringUtils.hasText(token) || !token.startsWith("Bearer ")) {
            throw new BusinessException(ResultCode.UNAUTHORIZED);
        }
        
        // 提取token
        token = token.substring(7);
        
        // 验证token是否有效
        if (!jwtUtil.validateToken(token)) {
            throw new BusinessException(ResultCode.UNAUTHORIZED);
        }
        
        // 将用户ID存入请求属性
        request.setAttribute("userId", jwtUtil.getUserIdFromToken(token));
        request.setAttribute("username", jwtUtil.getUsernameFromToken(token));
        
        return true;
    }
    
    /**
     * 判断是否是不需要验证token的路径
     */
    private boolean isExcludedUri(String uri) {
        return uri.contains("/login") || 
               uri.contains("/register") || 
               uri.contains("/actuator");
    }
} 